package xyz.xcvu.ma2.module;

import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

@Component
@MagicModule("convert")
public class ConvertUtil {

    @Comment("inputStream转outputStream")
    public ByteArrayOutputStream isToOs(
            @Comment("InputStream") final InputStream inS
    ) throws Exception {
        final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        int ch;
        while ((ch = inS.read()) != -1) {
            swapStream.write(ch);
        }
        return swapStream;
    }

    @Comment("outputStream转inputStream")
    public ByteArrayInputStream osToIs(
            @Comment("OutputStream") final OutputStream outS
    ) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos = (ByteArrayOutputStream) outS;
        final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        return swapStream;
    }

    @Comment("inputStream转String")
    public String isToStr(
            @Comment("InputStream") final InputStream inS
    ) throws Exception {
        final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        int ch;
        while ((ch = inS.read()) != -1) {
            swapStream.write(ch);
        }
        return swapStream.toString();
    }

    @Comment("OutputStream 转String")
    public String osToStr(
            @Comment("OutputStream") final OutputStream outS
    ) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos = (ByteArrayOutputStream) outS;
        final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        return swapStream.toString();
    }

    @Comment("String转inputStream")
    public ByteArrayInputStream strToIs(
            @Comment("String") final String str
    ) throws Exception {
        final ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes());
        return input;
    }

    @Comment("String 转outputStream")
    public ByteArrayOutputStream strToOs(
            @Comment("String") final String str
    ) throws Exception {
        return isToOs(strToIs(str));
    }
}
